<template>
  <div class="app-container">
    <el-row :gutter="20" class="div-height-left">
      <el-col v-if="userInfo.userId === '1'" :span="4" class="div-height-left">
        <sys-org-tree @treeClick="treeClick"/>
      </el-col>
      <el-col :span="userInfo.userId === '1' ? 20 : 24" :xs="24">
        <div class="search-container">
          <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams"
                   label-width="100px">
            <el-form-item label="项目分类" prop="itemClass">
              <el-select v-model="queryParams.itemClass" class="width-120" clearable filterable
                         placeholder="请选择项目分类"
                         @change="getList">
                <el-option v-for="dict in dictDataMap['bill_item_class_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <el-form-item label="项目代码" prop="itemCode">
              <el-input v-model="queryParams.itemCode" clearable placeholder="请输入项目代码"
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="项目名称" prop="itemName">
              <el-input v-model="queryParams.itemName" clearable placeholder="请输入项目名称"
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="门诊费用分类" prop="classOnRcpt">
              <el-select v-model="queryParams.classOnRcpt" class="width-120" clearable filterable
                         placeholder="请选择门诊费用分类" @change="getList">
                <el-option v-for="dict in dictDataMap['outp_rcpt_fee_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <el-form-item label="住院费用分类" prop="classOnInp">
              <el-select v-model="queryParams.classOnInp" class="width-120" clearable filterable
                         placeholder="请选择住院费用分类"
                         @change="getList">
                <el-option v-for="dict in dictDataMap['inp_rcpt_fee_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <el-form-item label="核算项目分类" prop="classOnReckoning">
              <el-select v-model="queryParams.classOnReckoning" class="width-120" clearable filterable
                         placeholder="请选择核算项目分类" @change="getList">
                <el-option v-for="dict in dictDataMap['reck_item_class_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <el-form-item label="会计科目" prop="subjCode">
              <el-select v-model="queryParams.subjCode" class="width-120" clearable filterable
                         placeholder="请选择会计科目"
                         @change="getList">
                <el-option v-for="dict in dictDataMap['tally_subject_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <el-form-item filterable label="病案首页分类" prop="classOnMr">
              <el-select v-model="queryParams.classOnMr" class="width-120" clearable
                         placeholder="请选择病案首页分类"
                         @change="getList">
                <el-option v-for="dict in dictDataMap['mr_fee_class_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <el-form-item label="拼音码" prop="inputCode">
              <el-input v-model="queryParams.inputCode" clearable placeholder="请输入拼音码"
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <!-- //            <el-form-item label="开始时间" prop="startDate">-->
            <!--                <el-date-picker clearable-->
            <!--                                v-model="queryParams.startDate"-->
            <!--                                type="date"-->
            <!--                                value-format="yyyy-MM-dd"-->
            <!--                                placeholder="请选择开始时间">-->
            <!--                </el-date-picker>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="停止时间" prop="stopDate">-->
            <!--                <el-date-picker clearable-->
            <!--                                v-model="queryParams.stopDate"-->
            <!--                                type="date"-->
            <!--                                value-format="yyyy-MM-dd"-->
            <!--                                placeholder="请选择停止时间">-->
            <!--                </el-date-picker>-->
            <!--            </el-form-item>-->
            <!--                    <el-form-item>-->
            <!--                        -->
            <!--                    </el-form-item> -->
            <div class="mr20" style="float: right">
              <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
            </div>
          </el-form>
        </div>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPerm="['base:priceList:add']" :disabled="!queryParams.orgId" plain
                       type="primary"
                       @click="handleAdd">
              <template #icon>
                <i-ep-plus/>
              </template>
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              plain
              type="info"
              @click="handleImport"
            >
              <template #icon>
                <i-ep-upload/>
              </template>
              导入数据、导出模板
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPerm="['base:priceList:export']" :disabled="!queryParams.orgId" plain
                       type="warning"
                       @click="handleExport">
              <template #icon>
                <i-ep-download/>
              </template>
              导出
            </el-button>
          </el-col>
        </el-row>

        <el-table v-adaptive :border="true" :cell-style="cellStyle" :data="priceListList"
                  :header-cell-style="$headerCellStyle"
                  :stripe="true" highlight-current-row>
          <el-table-column :align="'left'" label="项目分类" prop="itemClass" width="100px">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['bill_item_class_dict']" :value="scope.row.itemClass"/>
            </template>
          </el-table-column>
          <el-table-column :align="'left'" :show-overflow-tooltip="true" label="项目代码" min-width="100px"
                           prop="itemCode"/>
          <el-table-column :align="'left'" :show-overflow-tooltip="true" label="项目名称" min-width="180px"
                           prop="itemName"/>
          <el-table-column :align="'left'" :show-overflow-tooltip="true" label="项目规格" prop="itemSpec"/>
          <el-table-column :align="'left'" :show-overflow-tooltip="true" label="单位" prop="units"
                           width="80px">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.units"/>
            </template>
          </el-table-column>
          <el-table-column :align="'left'" :show-overflow-tooltip="true" label="现行(元)" prop="inForcePrice"
                           width="120px"/>
          <el-table-column :align="'left'" :show-overflow-tooltip="true" label="调价后价格(元)" prop="price"
                           width="105px">
            <template #default="scope">
              <span>{{ scope.row.inForceStopDate ? scope.row.price : "未调价" }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="新价格开始时间" prop="startDate" width="140">
            <template #default="scope">
              <span>{{
                  scope.row.inForceStopDate
                    ? $parseTime(scope.row.startDate, "{y}-{m}-{d} {h}:{i}:{s}")
                    : ""
                }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="停止时间" prop="stopDate" width="160">
            <template #default="scope">
              <span>{{ $parseTime(scope.row.stopDate, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'left'" :show-overflow-tooltip="true" label="医保编码" prop="itemCodeYbCompare"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="门诊费用分类"
                           min-width="100px"
                           prop="classOnRcpt">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['outp_rcpt_fee_dict']" :value="scope.row.classOnRcpt"/>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="住院费用分类"
                           min-width="100px"
                           prop="classOnInp">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['inp_rcpt_fee_dict']" :value="scope.row.classOnInp"/>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="核算项目分类"
                           min-width="100px"
                           prop="classOnReckoning">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['reck_item_class_dict']"
                             :value="scope.row.classOnReckoning"/>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="会计科目" min-width="100px"
                           prop="subjCode">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['tally_subject_dict']" :value="scope.row.subjCode"/>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="病案首页分类"
                           min-width="120px"
                           prop="classOnMr">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['mr_fee_class_dict']" :value="scope.row.classOnMr"/>
            </template>
          </el-table-column>
          <el-table-column :align="'left'" class-name="small-padding fixed-width" fixed="right" label="操作"
                           width="240px">
            <template #default="scope">
              <template v-if="scope.row.itemClass !== 'A' && scope.row.itemClass !== 'B'">
                <el-button v-if="!scope.row.stopDate" v-hasPerm="['base:priceList:priceAdjustment']"
                           type="warning"
                           @click="priceAdjustmentFun(scope.row)">
                  <template #icon>
                    <i-ep-edit/>
                  </template>
                  调价
                </el-button>
                <el-button v-hasPerm="['base:priceList:edit']" type="success"
                           @click="handleUpdate(scope.row)">
                  <template
                    #icon>
                    <i-ep-edit/>
                  </template>
                  修改
                </el-button>
                <el-button v-if="!scope.row.stopDate" v-hasPerm="['base:priceList:stopPrice']"
                           type="danger"
                           @click="stopPriceFun(scope.row)">
                  <template #icon>
                    <i-ep-delete/>
                  </template>
                  停价
                </el-button>
                <el-button v-if="scope.row.stopDate" v-hasPerm="['base:priceList:edit']" type="success"
                           @click="enable(scope.row)">
                  <template #icon>
                    <i-ep-document-add/>
                  </template>
                  启用
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                    :total="total" @pagination="getList"/>
      </el-col>
    </el-row>
    <!-- 添加或修改价表对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="1000px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="130px">
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="" prop="intoItemCheck">
              <el-checkbox v-model="intoItemCheck">{{ itemCheckName }}</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目分类" prop="itemClass">
              <el-select v-model="form.itemClass" filterable placeholder="请选择项目分类"
                         style="width: 100%">
                <el-option v-for="dict in billItemList" :key="dict.value" :disabled="dict.disabled"
                           :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目代码" prop="itemCode">
              <el-input v-model="form.itemCode" placeholder="请输入项目代码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入项目名称" @input="itemNameInput"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目规格" prop="itemSpec">
              <el-input v-model="form.itemSpec" placeholder="请输入项目规格"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="units">
              <el-select v-model="form.units" filterable placeholder="请选择单位" style="width: 100%">
                <el-option v-for="dict in dictDataMap['spec_unit']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" :disabled="isNotEdit" placeholder="请输入价格" type="number">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate" style="width: 100%">
              <el-date-picker v-model="form.startDate" :disabled="isNotEdit" clearable placeholder="请选择开始时间"
                              style="width: 100%" type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门诊费用分类" prop="classOnRcpt">
              <el-select v-model="form.classOnRcpt" filterable placeholder="请选择门诊费用分类"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['outp_rcpt_fee_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="住院费用分类" prop="classOnInp">
              <el-select v-model="form.classOnInp" filterable placeholder="请选择住院费用分类"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['inp_rcpt_fee_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="核算项目分类" prop="classOnReckoning">
              <el-select v-model="form.classOnReckoning" filterable placeholder="请选择核算项目分类"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['reck_item_class_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会计科目" prop="subjCode">
              <el-select v-model="form.subjCode" filterable placeholder="请选择会计科目"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['tally_subject_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="病案首页分类" prop="classOnMr">
              <el-select v-model="form.classOnMr" filterable placeholder="请选择病案首页分类"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['mr_fee_class_dict']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拼音码" prop="inputCode">
              <el-input v-model="form.inputCode" placeholder="请输入拼音码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自费或医保" prop="zfOrYb">
              <el-radio-group v-model="form.zfOrYb" style="width: 100%">
                <el-radio v-for="dict in dictDataMap['is_medical_insurance']" :key="dict.dictValue"
                          :value="dict.dictValue">{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医保对照项目代码" prop="itemCodeYbCompare">
              <el-input v-model="form.itemCodeYbCompare" placeholder="请输入医保对照项目代码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优惠价格" prop="preferPrice">
              <el-input v-model="form.preferPrice" placeholder="请输入优惠价格" type="number">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="网络价格" prop="networkPrice">
              <el-input v-model="form.networkPrice" placeholder="请输入网络价格" type="number">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批发价格" prop="tradePrice">
              <el-input v-model="form.tradePrice" placeholder="请输入批发价格" type="number">
                <template #appends>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注信息" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入内容" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="continuousAdd"><template
            #icon><i-ep-plus/></template>连续添加</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"><template
            #icon><i-ep-plus/></template>添
            加</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 调价弹出框 -->
    <price-adjustment ref="priceAdjustmentRef" @refreshParentList="getList"/>

    <!-- 价表信息导入对话框 -->
    <el-dialog v-model="uploadOpen" :title="upload.title" append-to-body width="400px" @close="dialogClose">
      <el-upload ref="uploadRef" :auto-upload="false" :http-request="httpRequest" :limit="1"
                 :on-change="handleChange" :on-progress="handleFileUploadProgress" accept=".xlsx" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入xlsx格式文件。</span>
          <el-link :underline="false" style="font-size:12px;vertical-align: baseline;" type="primary"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="dialogClose">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script lang="ts" setup>
import {
  addPriceList,
  delPriceList,
  getPriceList,
  priceEnable,
  selectPagePriceList,
  stopPrice,
  updatePriceList,
} from "@/api/base/priceList";
import priceAdjustment from "@/views/base/priceList/priceAdjustment.vue";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {firstLetterResult} from "@/utils/pinyin";
import {importDataPriceList} from "@/api/base/priceList.ts";

const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any;
const dictStore = useDictStoreHook();
const formRef = ref();
const priceAdjustmentRef = ref();
const dictDataMap = ref(
  dictStore.isTypeGetData(
    "tally_subject_dict",
    "bill_item_class_dict",
    "outp_rcpt_fee_dict",
    "inp_rcpt_fee_dict",
    "reck_item_class_dict",
    "mr_fee_class_dict",
    "spec_unit",
    "is_medical_insurance"
  )
);
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;

// 弹出框是否添加诊疗项目名称
const itemCheckName = ref("同时添加诊疗项目");

const fileData = ref<any>(null)  // 文件上传数据（多文件合一）
const fileList = ref([])  // upload多文件数组
const uploadRef = ref()

// 用户导入参数
const upload = ref<any>({
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
})
const uploadOpen = ref(false)
// 按钮loading
const buttonLoading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 价表表格数据
const priceListList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 是否生成诊疗项目
const intoItemCheck = ref<boolean>(true);
// 不能编辑
const isNotEdit = ref(false);
// 诊疗项目下拉框
const billItemList = ref<any[]>([]);
// 查询参数
const queryParamsRef = ref();
const queryParams = ref<PriceList>({
  pageNum: 1,
  pageSize: 10,
  itemClass: "",
  itemCode: "",
  itemName: "",
  itemSpec: "",
  medicalInsuranceType: "",
  units: "",
  networkPrice: 0,
  tradePrice: 0,
  price: 0,
  preferPrice: 0,
  classOnRcpt: "",
  classOnInp: "",
  classOnReckoning: "",
  subjCode: "",
  classOnMr: "",
  startDate: "",
  stopDate: "",
  inputCode: "",
  orgId: "",
  itemCodeYbCompare: "",
  zfOrYb: "",
});
// 表单参数
const form = ref<PriceList>({
  itemClass: "",
  itemCode: "",
  itemName: "",
  itemSpec: "",
  medicalInsuranceType: "",
  units: "",
  networkPrice: 0,
  tradePrice: 0,
  price: 0,
  preferPrice: 0,
  classOnRcpt: "",
  classOnInp: "",
  classOnReckoning: "",
  subjCode: "",
  classOnMr: "",
  startDate: proxy.$parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
  stopDate: null,
  inputCode: "",
  orgId: "",
  itemCodeYbCompare: "",
  zfOrYb: "",
});
// 表单校验
const rules = ref({
  // priceId: [
  //     { required: true, message: "主键不能为空", trigger: "blur" }
  // ],
  itemClass: [{required: true, message: "项目分类不能为空", trigger: "change"}],
  itemCode: [{required: true, message: "项目代码不能为空", trigger: "blur"}],
  itemName: [{required: true, message: "项目名称不能为空", trigger: "blur"}],
  itemSpec: [{required: true, message: "项目规格不能为空", trigger: "blur"}],
  medicalInsuranceType: [
    {required: true, message: "医保类型不能为空", trigger: "change"},
  ],
  units: [{required: true, message: "单位不能为空", trigger: "blur"}],
  price: [{required: true, message: "价格不能为空", trigger: "blur"}],
  classOnRcpt: [{required: true, message: "门诊费用分类不能为空", trigger: "change"}],
  classOnInp: [{required: true, message: "住院费用分类不能为空", trigger: "change"}],
  classOnReckoning: [
    {required: true, message: "核算项目分类不能为空", trigger: "change"},
  ],
  subjCode: [{required: true, message: "会计科目不能为空", trigger: "change"}],
  classOnMr: [{required: true, message: "病案首页分类不能为空", trigger: "change"}],
  startDate: [{required: true, message: "开始时间不能为空", trigger: "blur"}],
  orgId: [{required: true, message: "机构ID不能为空", trigger: "blur"}],
});
if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId;
  getList();
}

/** 设置单元格颜色 */
function cellStyle(row, _column, _rowIndex, _columnIndex) {
  if (
    row.row.inForceStopDate &&
    row.row.price &&
    (row.column.label === "调价后价格(元)" || row.column.label === "新价格开始时间")
  ) {
    return "color: #FF4949";
  }
}

/** 项目名称输入框改变事件 设置拼音码*/
function itemNameInput(value) {
  if (value) {
    form.value.inputCode = firstLetterResult(value);
  } else {
    form.value.inputCode = "";
  }
}

/** 左侧科室树节点点击事件 */
function treeClick(obj) {
  queryParams.value.orgId = obj.id;
  getList();
}

/** 查询价表列表 */
function getList() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择左侧所属机构后查询");
  }
  selectPagePriceList(queryParams.value).then((response: any) => {
    priceListList.value = response.rows;
    total.value = response.total;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    itemClass: "",
    itemCode: "",
    itemName: "",
    itemSpec: "/",
    medicalInsuranceType: "",
    units: "",
    networkPrice: 0,
    tradePrice: 0,
    price: 0,
    preferPrice: 0,
    classOnRcpt: "",
    classOnInp: "",
    classOnReckoning: "",
    subjCode: "",
    classOnMr: "",
    startDate: proxy.$parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
    stopDate: "",
    inputCode: "",
    remark: "",
    itemCodeYbCompare: "",
    zfOrYb: "1",
    orgId: queryParams.value.orgId,
  };
  disposeAddBillItemList();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item) => item.priceId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isNotEdit.value = false;
  itemCheckName.value = "同时添加诊疗项目";
  // this.billItemList = this.dictDataMap['bill_item_class_dict
  open.value = true;
  title.value = "添加价表";
}

/** 处理新增页面诊疗项目分类数据 */
function disposeAddBillItemList() {
  billItemList.value = [];
  dictDataMap.value["bill_item_class_dict"].forEach((item) => {
    let billItem: any = {
      value: item.dictValue,
      label: item.dictLabel,
    };
    if (item.dictValue === "A" || item.dictValue === "B") {
      billItem.disabled = true;
    }
    billItemList.value.push(billItem);
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  isNotEdit.value = true;
  itemCheckName.value = "同时修改诊疗项目";
  const priceId = row.priceId || ids.value;
  getPriceList(priceId).then((response: any) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改价表";
  });
}

/** 调价 */
function priceAdjustmentFun(row) {
  getPriceList(row.priceId).then((res) => {
    const data = res.data;
    if (row.price !== data.price) {
      let msg =
        "此项目价格已修改，现价为" +
        data.price +
        "元，新价启用时间为" +
        data.startDate +
        ",若需要继续调整价格，请点击‘继续调价’按钮";
      ElMessageBox.confirm(msg, "提示", {
        confirmButtonText: "继续调价",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          openPriceAdjustment(data);
        })
        .catch(() => {
          ElMessage.info({message: "已取消调价，页面已刷新"});
          getList();
        });
    } else {
      openPriceAdjustment(data);
    }
  });
}

function openPriceAdjustment(data) {
  nextTick(() => {
    priceAdjustmentRef.value.priceAdjustmentShow(data);
  });
}

/** 连续添加 */
function continuousAdd() {
  submitForm("1");
}

/** 提交按钮 */
function submitForm(type) {
  // 当type = 1 为连续添加弹出框不关闭， 否则关闭
  form.value.intoItemCheck = intoItemCheck.value;
  (formRef.value as any).validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.priceId != null) {
        updatePriceList(form.value)
          .then((_response) => {
            ElMessage.success("修改成功");
            reset();
            if (type !== "1") {
              open.value = false;
            }
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      } else {
        addPriceList(form.value)
          .then((_response) => {
            ElMessage.success("新增成功");
            reset();
            if (type !== "1") {
              open.value = false;
            }
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      }
    }
  });
}

/** 启用 */
function enable(row) {
  ElMessageBox.confirm("确定要将" + row.itemName + "项目启用？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(function () {
      priceEnable(row).then(() => {
        getList();
        ElMessage.success("启用成功");
      });
    })
    .catch(() => {
    });
}

/** 停价 */
function stopPriceFun(row) {
  ElMessageBox.confirm("确定要将" + row.itemName + "项目停价吗？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(function () {
      stopPrice(row.priceId).then(() => {
        getList();
        ElMessage.success("停价成功");
      });
    })
    .catch(() => {
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const priceIds = row.priceId || ids.value;
  ElMessageBox.confirm('是否确认删除价表编号为"' + priceIds + '"的数据项？', {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delPriceList(priceIds).then(() => {
        getList();
        ElMessage.success("删除成功");
      });
    })
    .catch(() => {
    });
}

/** 导出按钮操作 */
function handleExport() {
  // this.download('admin/priceList/export', {
  //     ...this.queryParams
  // }, `priceList_${new Date().getTime()}.xlsx`)
}


/** 导入按钮操作 */
function handleImport() {
  upload.value.title = "药品基本信息导入";
  uploadOpen.value = true;
}

function dialogClose() {
  fileData.value = []
  fileList.value = []
  uploadRef.value.clearFiles()
  getList()
  uploadOpen.value = false;
}

// 文件上传中处理
function handleFileUploadProgress(event, file, fileList) {
  upload.value.isUploading = true;
}


function httpRequest(file) {
  fileData.value.append('file', file.file) // append增加数据
}

//监控上传文件列表
function handleChange(file, fileListInfo) {
  let existFile = fileListInfo.slice(0, fileListInfo.length - 1).find((f) => f.name === file.name)
  if (file.name.substring(file.name.lastIndexOf(".") + 1, file.name.length) !== 'xlsx') {
    fileListInfo.pop()
    return ElMessage.error('上传的文件类型不是.xlsx文件，请重新上传!')
  }
  if (existFile) {
    ElMessage.error('当前文件已经存在!')
    fileListInfo.pop()
  }
  fileList.value = fileListInfo
}

/** 下载模板操作 */
function importTemplate() {
  // this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
}


function submitFileForm() {
  const link = document.createElement('a')
  fileData.value = new FormData() // new formData对象
  uploadRef.value.submit() // 提交调用uploadFile函数
  importDataPriceList(fileData.value).then((res: resType) => {
    ElMessage.success("正在导入，请稍等...")
    setTimeout(() => {
      dialogClose()
    }, 5000)
    debugger
    if (res.data.size > 0) {
      const blob = new Blob([res.data], {type: 'application/octet-stream'})
      link.download = "价表数据导入-错误数据.xlsx"
      let objectUrl = URL.createObjectURL(blob)
      link.href = objectUrl
      document.body.appendChild(link)
      // 下载文件
      link.click()
      // 释放内存
      window.URL.revokeObjectURL(objectUrl)
      document.body.removeChild(link)
    } else {
      ElMessage.success("导入成功")
    }
  })
}


</script>
<script lang="ts">
export default {
  name: "PriceList",
};
</script>
